package top.kaoshanji.p1ch04a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代码清单-p1ch04a-73页a：流是什么
 * author kaoshanji
 * ^_^
 * create time 2025/2/10 18:47
 */
public class StreamBasic {

    private static final Logger logger = LogManager.getLogger(StreamBasic.class);

    public static void main(String[] args) {
        logger.info("...代码清单-p1ch04a-73页a：流是什么...");

        // 基于Java7语法
        getLowCaloricDishesNamesInJava7(Dish.menu).forEach(System.out::println);

        System.out.println("---");

        // 基于Java8语法
        getLowCaloricDishesNamesInJava8(Dish.menu).forEach(System.out::println);

    }


    public static List<String> getLowCaloricDishesNamesInJava7(List<Dish> dishes) {
        List<Dish> lowCaloricDishes = new ArrayList<>();

        // 过滤
        for (Dish dish: dishes) {
            if (dish.getCalories() < 400) {
                lowCaloricDishes.add(dish);
            }
        }

        // 排序
        Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
            @Override
            public int compare(Dish o1, Dish o2) {
                return Integer.compare(o1.getCalories(), o2.getCalories());
            }
        });

        // 排序之后的结果
        List<String> lowCaloricDishesName = new ArrayList<>();
        for (Dish dish: lowCaloricDishes) {
            lowCaloricDishesName.add(dish.getName());
        }

        return lowCaloricDishesName;
    }

    public static List<String> getLowCaloricDishesNamesInJava8(List<Dish> dishes) {
        return dishes.stream()
                .filter(d -> d.getCalories() < 400)
                .sorted(Comparator.comparing(Dish::getCalories))
                .map(Dish::getName)
                .collect(Collectors.toList());
    }

}
